package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-gin-admin/model"
	"github.com/go-gin-admin/util"
	"net/http"
	"time"
)

// 新建部门
func AddDept(c *gin.Context) {
	var deptData model.Dept
	if err := c.BindWith(&deptData, binding.JSON); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("参数解析错误"))
		return
	}
	local := time.Now().Local()
	deptData.CreateTime = local
	deptData.UpdateTime = local
	insertId, err := deptData.InsertDept()
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("新建失败"))
		return
	}
	m := make(map[string]interface{})
	m["insertId"] = insertId
	c.JSON(http.StatusOK, new(util.Response).Ok("新建成功", m))
}

// 获取tree结构部门
func GetDeptTree(c *gin.Context) {
	var deptData model.Dept
	deptTree, err := deptData.GetDeptTree()
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("查询失败"))
		return
	}
	m := make(map[string]interface{})
	m["deptTree"] = deptTree
	c.JSON(http.StatusOK, new(util.Response).Ok("", m))
}

// 更新部门信息
func UpdateDept(c *gin.Context) {
	var deptData model.Dept
	if err := c.BindWith(&deptData, binding.JSON); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("参数解析错误"))
		return
	}
	deptData.UpdateTime = time.Now().Local()
	if err := deptData.UpdateDept(); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("修改失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("修改成功", nil))
}

// 删除部门
func DeleteDept(c *gin.Context) {
	var deptData model.Dept
	deptId, _ := util.StringToInt64(c.Param("deptId"))
	if err := deptData.RemoveDept(deptId); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("删除失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("修改成功", nil))
}
